<?php

namespace app\common\model\product;

use app\api\model\supplier\Supplier as SupplierModel;
use app\common\library\helper;
use app\common\model\BaseModel;
use app\common\model\user\Grade;
use app\common\model\user\User;
use think\facade\Cache;
use think\facade\Db;

/**
 * 商品模型
 */
class CarQueryLog extends BaseModel
{
    protected $name = 'car_query_log';
    
    public function car()
    {
        return $this->belongsTo('Car', 'car_id');
    }


    public static function checkSearch($user_id)
    {
        $default_times = 3;
        //查询用户等级
        $grade_id  = User::where(['is_delete' => 0, 'user_id' => $user_id])->value('grade_id');
        $grade_obj = Grade::where(['is_delete' => 0, 'grade_id' => $grade_id])->find();
        //如果是默认等级，查询次数为固定
        if(empty($grade_obj) || $grade_obj['is_default'] == 1){
            //获取用户总查询次数
            $count = self::where(['user_id' => $user_id, 'app_id' => 1001])->count('DISTINCT car_id');
            if($count >= $default_times)
            {
                return [false,'查询次数已用完'];
            }
        }else{//如果非默认等级，则查询对应的日查询次数和年查询次数

            $default_year_times =  $grade_obj->year_times;
            $default_day_times  =  $grade_obj->day_times;
            //查询年次数
            $start_year = strtotime(date('Y').'-01-01 00:00:00');
            $end_year   = strtotime(date('Y').'-12-31 23:59:59');

            $count = self::where(['user_id' => $user_id, 'app_id' => 1001])->whereBetween('create_time',[$start_year, $end_year])->count('DISTINCT car_id');
            if($count >= $default_year_times)
            {
                return [false,'查询次数已用完'];
            }

            //查询日次数
            $start_day = strtotime(date('Y-m-d') . ' 00:00:00');
            $end_day   = strtotime(date('Y-m-d') . ' 23:59:59');

            $count = self::where(['user_id' => $user_id, 'app_id' => 1001])->whereBetween('create_time',[$start_day, $end_day])->count('DISTINCT car_id');
            if($count >= $default_day_times)
            {
                return [false,'查询次数已用完'];
            }



        }
        return [true,''];
    }


}
